/**
 * @(#) OverView.as
 *
 * @date		2009. 04. 20.
 * @version		1.0
 * @author		Jo, ChangHun
 * @description	연말정산 메인 view - Mediator
 * 				연말정산 - 탭3 인적기본공제 팝업창 Logic을 관리 
 */
package com.skt.common_hr.yearadjustment.view
{
	import com.skt.common_hr.common.PsHrAlert;
	import com.skt.common_hr.common.Variables;
	import com.skt.common_hr.common.puremvc.CommonMediator;
	import com.skt.common_hr.yearadjustment.YearAdjustmentFacade;
	import com.skt.common_hr.yearadjustment.model.BasicSubtractionProxy;
	import com.skt.common_hr.yearadjustment.model.vo.DependentFamilyVO;
	import com.skt.common_hr.yearadjustment.view.components.popBasicSubtraction;
	import com.wcl.utils.DateUtil;
	import com.wcl.utils.StringUtil;
	
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	import mx.managers.PopUpManager;
	
	import org.puremvc.as3.multicore.interfaces.INotification;
	

	public class popBasicSubtractionMediator extends CommonMediator
	{
		public static const NAME:String = "popBasicSubtractionMediator"; 
		
		public var dependentFamily:ArrayCollection = new ArrayCollection();
		[Bindable] public var relationComboData:ArrayCollection = new ArrayCollection();
		public var v_year:String = "";
		[Bindable] public var v_enable:Boolean = true;
		
		//2013
		[Bindable] static public var comboFamily_Hnd:ArrayCollection = new ArrayCollection();
		
		[Bindable] static public var comboFamily:ArrayCollection = new ArrayCollection();
		[Bindable] static public var comboFamilyType:ArrayCollection = new ArrayCollection();

		/**
		* 생성자
		* 
		* @param
		* @return void
		*/
        public function popBasicSubtractionMediator( viewComponent:Object )
        {
            super( NAME, viewComponent );
            view.callLater(initView);
        }
 		
		/**
		* View를 초기화 한다.
		*	- View에 기본사항을 출력하고 data를 load
		* @param
		* @return void
		*/
 		public function initView():void
 		{
 			view.addEventListener(popBasicSubtraction.CancelInput, onCancelInput);
 			view.addEventListener(popBasicSubtraction.OkInput, onOkInput);
 			view.addEventListener(popBasicSubtraction.CLICK_ADD_FAMILY, onClickAddFamily);
 			view.addEventListener(popBasicSubtraction.CLICK_DEL_FAMILY, onClickDelFamily);
 			
 			view._isEnable = v_enable;
 			view._isEnable = v_enable;
 			view.basicPopYear = v_year;
 			//selectFamilyData();
 			selectComboFamily();
 		}
 		
 		//인적공제 CNT RELOAD
 		private function selectSubtractionCnt():void{
 			var proxy:BasicSubtractionProxy = facade.retrieveProxy(BasicSubtractionProxy.NAME) as BasicSubtractionProxy;
 			proxy.load(Variables.yearPernr, v_year);
 		}
 		
 		//관계 콤보박스 데이터 조회
 		private function selectComboFamily():void{
 			var proxy:BasicSubtractionProxy = facade.retrieveProxy(BasicSubtractionProxy.NAME) as BasicSubtractionProxy;
 			proxy.comboload(v_year);
 		}
 		
 		//관계 콤보박스 데이터 조회
 		private function loadComboFamilyType():void{
 			var proxy:BasicSubtractionProxy = facade.retrieveProxy(BasicSubtractionProxy.NAME) as BasicSubtractionProxy;
 			proxy.loadTypeComobo(v_year);
 		}
 
 
 		private function selectFamilyData():void{
 			var proxy:BasicSubtractionProxy = facade.retrieveProxy(BasicSubtractionProxy.NAME) as BasicSubtractionProxy;
 			//Alert.show("selectFamilyData: " + v_year);
 			proxy.familyLoad(Variables.yearPernr, v_year);
 		}
 		
 		private function onOkInput(event:Event):void{
 			
 			var detailList:Array = new Array();
	 		//for each(var rec:DependentFamilyVO in view.dependentFamily)
	 		var obj:Object;
	 		for each(var rec:Object in view.dependentFamily)
	 		{
	 			obj = {};
	 			//필수입력값들이 없는 항목들은 무시
	 			if(StringUtil.NVL(rec["KDSVH"]) == "" && StringUtil.NVL(rec["LNMHG"]) == "" && StringUtil.NVL(rec["FNMHG"]) == ""
	 			   && StringUtil.NVL(rec["REGNO"]) == ""){
	 				continue;
	 			}
	 			
	 			//주민등록번호 형식 체크(예외 주민번호 때문에.. RFC에서 체크로 변경)
	 			//if(!isValidation(StringUtil.NVL(rec["REGNO"]), rec.KDSVH, rec.LNMHG+rec.FNMHG)  ){
	 			//	return;
	 			//}
	 			rec["BEGDA"] = null;
//	 			if(rec.ADPDT != null){
//	 				rec["ADPDT"] = DateUtil.toBasicString(rec.ADPDT);	
//	 			}
	 			
	 			
	 			obj.ADCID = rec.ADCID;
				obj.ADPDT = DateUtil.toBasicString(rec.ADPDT);
				obj.ATEXT = rec.ATEXT;
				obj.bCanDEL = rec.bCanDEL;
				obj.BEGDA = rec.BEGDA; 
				obj.birth = rec.birth;
				obj.CHDID = rec.CHDID;
				obj.DPTID = rec.DPTID;
				obj.DPTXT = rec.DPTXT;
				obj.DPTYP = rec.DPTYP;
				obj.FNAGBN = rec.FNAGBN;
				obj.FNMHG = rec.FNMHG;
				obj.HNDID = rec.HNDID;
				obj.KDSVH = rec.KDSVH;
				obj.LNMHG = rec.LNMHG;
				obj.OBJPS = rec.OBJPS;
				obj.REGNO = rec.REGNO;
				obj.STEXT = rec.STEXT;
				obj.SUBTY = rec.SUBTY;
				obj.WOMEE = rec.WOMEE;
	 			
	 			//2013
	 			obj.HNDCD = StringUtil.NVL(rec.HNDCD);
	 			obj.SIGPR = rec.SIGPR;
	 			
	 			detailList.push(obj);
	 		}
 			
 			//중복된 주민등록번호 체크
 			//if(!arrDataCheck(detailList, "REGNO")){
	 		//	return;
	 		//}
	 		
	 		var proxy:BasicSubtractionProxy = facade.retrieveProxy(BasicSubtractionProxy.NAME) as BasicSubtractionProxy;
 			proxy.save(Variables.yearPernr, v_year, detailList); 	
 		}
 		
 		//중복 값 체크
 		private function arrDataCheck(arr:Array, str:String):Boolean{
 			var tmpVal:String = "";
 			for(var i:int=0; i < arr.length; i++){
 				tmpVal = arr[i][str];
 				for(var j:int=i+1; j < arr.length; j++){
 					if(tmpVal == arr[j][str]){
 						PsHrAlert.showMessage("주민등록번호가 중복 입력되었습니다.");
 						return false;
 					}
 				}
 			}
 			return true;
 		}

//shgoo 2010.01.07
/* 		
 		//저장 벨리데이션 체크
 		private function isValidation(val:String):Boolean{
 			var asum:int = 0;
		    var jArr:Array = new Array(2,3,4,5,6,7,8,9,2,3,4,5);
		    var bArr:Array = new Array(10,30,70,10,30,70,10,30,5,10);
		 	var pnum:String = val;
		 	if (pnum.length == 13) {
				for (var i:int=0; i< jArr.length; i++) {
		        	asum += parseInt(pnum.substr(i, 1)) * jArr[i];
		        }
		        var achk:String  = pnum.substr(12,1);
		        var bchk:int  = (11-(asum%11))%10;
		        if (parseInt(achk) == bchk) {
		        	return true;
		        }
		        PsHrAlert.showMessage("주민등록번호 형식이 맞지 않습니다.");
 				return false;
		    }else if(pnum.length == 0){
		        PsHrAlert.showMessage("주민등록번호를 입력해주세요.");
 				return false;
		    }
		    return false;
 		}
*/
 		//저장 벨리데이션 체크
 		private function isValidation(val:String, rel:String, ename:String):Boolean{
 			var asum:int = 0;
		    var jArr:Array = new Array(2,3,4,5,6,7,8,9,2,3,4,5);
//shgoo 
//		    var bArr:Array = new Array(10,30,70,10,30,70,10,30,5,10);
		 	var pnum:String = val;

        	if(!isValidDate(pnum)) {
        		PsHrAlert.showMessage(ename+"님의 주민등록번호 형식이 맞지 않습니다.");
				return false;
        	}

		 	if (pnum.length == 13) {
				
				for (var i:int=0; i< jArr.length; i++) {
		        	asum += parseInt(pnum.substr(i, 1)) * jArr[i];
		        }
		        
		        var achk:String  = pnum.substr(12,1);
		        var bchk:int = 0;
		        
		        if(parseInt(pnum.substr(6,1)) >= 5) {	//외국인
		        	bchk  = 11 - (asum%11);
		        	if(bchk >= 10)
		        		bchk = bchk - 10;
		        	bchk = bchk + 2;
		        	if(bchk >= 10)
		        		bchk = bchk - 10;	
		        }
		        else {
//shgoo 2010.01.13 7번째 자리수가 3인경우가 있어서 성별체크 로직 제거
/*		        	
		        	if(!isValidSex(pnum.substr(6,1), rel)) {
				        PsHrAlert.showMessage("주민등록번호 형식이 맞지 않습니다.");
 						return false;
		        	}
*/

		        	bchk  = (11-(asum%11))%10;
		        }
		        
		        if (parseInt(achk) == bchk) {
		        	return true;
		        }
		        
		        PsHrAlert.showMessage(ename+"님의 주민등록번호 형식이 맞지 않습니다.");
 				return false;
		    }else if(pnum.length == 0){
		       // PsHrAlert.showMessage("주민등록번호를 입력해주세요.");
 				return false;
		    }
		    return false;
 		}
 		
 		//선택된 관계에 따른 성별 체크
//shgoo 2010.01.13 7번째 자리수가 3인경우가 있어서 성별체크 로직 제거
/* 		
 		private function isValidSex(val:String, rel:String):Boolean {
			if(rel == "10" || rel == "12" || rel == "20" || rel == "22" || 
				rel == "40" || rel == "50" || rel == "51") {	//10:조부, 12:주부(배우자), 20:부, 22:부(배우자), 40:아들, 50:형, 51:제, 54:형제(배우자)
				if(val == "1")	return true;	//남자
				else	return false;
			}	
			else if(rel == "11" || rel == "13" || rel == "21" || rel == "23" || 
				rel == "41" || rel == "52") {	//11:조모, 13:조모(배우자), 21:모, 23:모(배우자), 41:딸, 52:자매
				if(val == "2")	return true;	//여자
				else	return false;
			}
			
			return true;
 		}
*/

 		//주민번호의 앞 6자리 체크
 		private function isValidDate(val:String):Boolean {
			var month:String = val.substr(2,2);
			var day:String = val.substr(4,2);
				
			if(parseInt(month) > 12 || parseInt(month) < 1 || parseInt(day) > 31 || parseInt(day) < 1)	return false;
			else return true;
 		}
////////////////////////////////////
 		
 		private function onCancelInput(event:Event):void
 		{
 			facade.removeMediator(popBasicSubtractionMediator.NAME);
 			PopUpManager.removePopUp(view);
 		}

		private function onClickAddFamily(event:Event):void {
 			var obj:DependentFamilyVO = new DependentFamilyVO();
 			obj.FNAGBN	= "";
			obj.SUBTY	= "";
			obj.STEXT	= "";
			obj.OBJPS	= "";
			obj.KDSVH	= "";
			obj.ATEXT	= "";
			obj.DPTYP	= "";
			obj.DPTXT	= "";
			obj.LNMHG	= "";
			obj.FNMHG	= "";
			obj.REGNO	= "";
			obj.DPTID	= "";
			obj.HNDID	= "";
			obj.WOMEE	= "";
			obj.CHDID	= "";
			obj.ADCID	= "";
			obj.ISNEW 	= '1';
 			view.dependentFamily.addItem(obj);
		}
		
		private function onClickDelFamily(event:Event):void {
 			view.dependentFamily.removeItemAt(view.famailyDg.selectedIndex);
		}
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Process MVC Messages
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		* 본 Class에서 처리해야할 Noti들을 등록한다.
		* 
		* @param
		* @return void
		*/
		override public function listNotificationInterests():Array
		{
			return [
					YearAdjustmentFacade.LOAD_DEPENDENT_FAMILY_COMPLETE,
					YearAdjustmentFacade.LOAD_DEPENDENT_FAMILY_FAILED,
					YearAdjustmentFacade.SAVE_DEPENDENT_FAMILY_COMPLETE,
					YearAdjustmentFacade.SAVE_DEPENDENT_FAMILY_FAILED,
					YearAdjustmentFacade.LOAD_COMBO_FAMILY_COMPLETE,
					YearAdjustmentFacade.LOAD_COMBO_FAMILY_FAILED,
					YearAdjustmentFacade.LOAD_COMBO_FAMILY_TYPE_COMPLETE
					];
		}
		

		/**
		* Noti별로 처리한다.
		* 
		* @param
		* @return void
		*/
		override public function handleNotification(note:INotification):void
		{
			switch(note.getName()) 
			{
				case YearAdjustmentFacade.LOAD_DEPENDENT_FAMILY_COMPLETE:
					//selectComboFamily();
					//loadComboFamilyType();
					preDependent((note.getBody() as BasicSubtractionProxy).dependentFamily);
					break;
				case YearAdjustmentFacade.LOAD_DEPENDENT_FAMILY_FAILED:
					trace("YearAdjustmentFacade.LOAD_DEPENDENT_FAMILY_FAILED");
					break;
				case YearAdjustmentFacade.SAVE_DEPENDENT_FAMILY_COMPLETE:
					onCancelInput(null);
					selectSubtractionCnt();
					//facade.sendNotification(YearAdjustmentView.CHECK_REQ_BASICSUBTRACTION);
					facade.sendNotification(YearAdjustmentFacade.RELOAD_BASIC_DATA);
					break;	
				case YearAdjustmentFacade.SAVE_DEPENDENT_FAMILY_FAILED:
					trace("YearAdjustmentFacade.SAVE_DEPENDENT_FAMILY_FAILED");
					//setStatusMessage((note.getBody() as BasicSubtractionProxy).msgStr);
					PsHrAlert.showMessage((note.getBody() as BasicSubtractionProxy).msgStr);
					break;	
				case YearAdjustmentFacade.LOAD_COMBO_FAMILY_COMPLETE:
					//selectFamilyData();
		 			loadComboFamilyType();
					comboFamily = (note.getBody() as BasicSubtractionProxy).comboFamily;
					trace("comboFamily : " + comboFamily.length);
					break;	
				case YearAdjustmentFacade.LOAD_COMBO_FAMILY_TYPE_COMPLETE:
					selectFamilyData();
					comboFamilyType = (note.getBody() as BasicSubtractionProxy).comboFamilyType;
					comboFamily_Hnd = (note.getBody() as BasicSubtractionProxy).comboHndType;
					break;	
				case YearAdjustmentFacade.LOAD_COMBO_FAMILY_FAILED:
					trace("YearAdjustmentFacade.LOAD_COMBO_FAMILY_FAILED");
					break;	
				default:
					//trace(this.instanceID+"에서 처리 안된 Noti가 검출됨 : " + note.getBody());
					break;
			}
		}
 		
 		private function preDependent(arr:ArrayCollection):void{
 			
 			for each(var vo:DependentFamilyVO in arr) {
				if(vo.SUBTY == "") {
					vo.STEXT = "본인";
				} 				
 			}
 			view.dependentFamily = arr;
 		}
 		
 		
		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Utility Functions
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
        private function get view():popBasicSubtraction
        {
            return viewComponent as popBasicSubtraction;
        }
	}
}